//
//  ZREmoticonManger.swift
//  Sina
//
//  Created by 张锐 on 16/3/8.
//  Copyright © 2016年 zhangr. All rights reserved.
//

import UIKit

class ZREmoticonManger: NSObject {
    
    static var recentEmoticons = [ZREmoticonModel]()
    
    static var defaultEmoticons = ZREmoticonManger.readEmoticonsByPackageName("com.sina.default")
    
    static var emojiEmoticons = ZREmoticonManger.readEmoticonsByPackageName("com.apple.emoji")
    
    static var lxhEmoticons = ZREmoticonManger.readEmoticonsByPackageName("com.sina.lxh")
    
    class func getAllEmoticons()->([[[ZREmoticonModel]]]){
    
        return [pageEmoticons(recentEmoticons),pageEmoticons(defaultEmoticons),pageEmoticons(emojiEmoticons),pageEmoticons(lxhEmoticons)]
    
    }
    
    /**
     通过输入包名 获得其中的Info文件，然后转换成模型，返回模型数组
     
     - parameter packageName: 包名
     
     - returns: 模型数组
     */
    class func readEmoticonsByPackageName(packageName : String) -> [ZREmoticonModel] {
        
        var result :[ZREmoticonModel] = [ZREmoticonModel]()
        
        let bundlePath = NSBundle.mainBundle().pathForResource("Emoticons.bundle", ofType: nil)
        
        let packagePath = (bundlePath! as NSString).stringByAppendingPathComponent(packageName)
        
        let filePath = (packagePath as NSString).stringByAppendingPathComponent("info.plist")
        
        let file = NSDictionary(contentsOfFile: filePath)
        
        let emoctions = file!["emoticons"] as! [[String : NSObject]]
        
        for emoction in emoctions{
        
            let emoctionModel = ZREmoticonModel(dict: emoction)
            
            emoctionModel.packagePath = "\(packagePath)"
        
            result.append(emoctionModel)
        }
        
        return result
        
    }
    /**
     输入一个emoticon数组 返回分页后的数组
     
     - returns: 分页后的数组
     */

    class func pageEmoticons(emoticons :[ZREmoticonModel]) -> [[ZREmoticonModel]]{
    
        let page  = (emoticons.count - 1) / 20 + 1
        
        var lenth = 20
        
        var result :[[ZREmoticonModel]] = [[ZREmoticonModel]]()
       
        for i in 0..<page{
            
        
            if i == page - 1{
            
                lenth = emoticons.count - i * 20
            
            }
            
            result.append((emoticons as NSArray).subarrayWithRange(NSMakeRange(i * 20, lenth)) as! [ZREmoticonModel])
        
        }
        
        return result
    
    }
    /**
     添加最近使用表情的方法
     */
    class func addRecentEmoticon (emoticon : ZREmoticonModel){
        
        if recentEmoticons.contains(emoticon){
        
            return
        
        }else{
        
            recentEmoticons.insert(emoticon, atIndex: 0)
        
        }
        
        //仅有一页 超过20个就删除最后一个
        if recentEmoticons.count > 20 {
        
            recentEmoticons.removeLast()
        
        }
        
    }

}
